<template>
  <aside class="sidebar" :style="{ width: sidebarWidth }">
    <!-- Element UI 菜单 -->
    <el-menu
      ref="menu"
      :default-active="activeMenu"
      :default-openeds="openMenus"
      class="el-menu-vertical-demo"
      @open="handleOpen"
      @close="handleClose"
      background-color="#545c64"
      text-color="#fff"
      active-text-color="#ffd04b"
      :collapse="isCollapse"
      :collapse-transition="false"
    >
      <!-- 聊天室 -->
      <el-submenu index="1">
        <template slot="title">
          <i class="el-icon-chat-line-round"></i>
          <span>房间列表</span>
        </template>
        <el-menu-item-group>
          <el-menu-item index="1-1" @click="navigateTo('/chat')">聊天室</el-menu-item>
          <el-menu-item index="1-2">AI陪聊</el-menu-item>
        </el-menu-item-group>
      </el-submenu>

      <!-- 用户管理 -->
      <el-submenu index="2">
        <template slot="title">
          <i class="el-icon-user-solid"></i>
          <span>后台管理</span>
        </template>
        <el-menu-item-group title="基础设置">
          <el-menu-item
            index="2-1"
            @click="navigateTo('/admin/forbidden-words')"
            :class="{ 'highlight': isCurrentRoute('/admin/forbidden-words') }"
          >
            违禁词设置
          </el-menu-item>
          <el-menu-item index="2-2">房间配置</el-menu-item>
        </el-menu-item-group>
        <el-menu-item-group title="高级设置">
          <!-- ✅ 修改为调用方法 -->
          <el-menu-item index="2-3" @click="goToUserManagement">用户管理</el-menu-item>
        </el-menu-item-group>
      </el-submenu>

      <!-- 系统日志 -->
      <el-menu-item index="3" disabled>
        <i class="el-icon-document"></i>
        <span>系统日志</span>
      </el-menu-item>

      <!-- 设置 -->
      <el-menu-item index="4" @click="navigateTo({ name: 'UserSettings' })">
        <i class="el-icon-setting"></i>
        <span>我的设置</span>
      </el-menu-item>
    </el-menu>

    <!-- 折叠按钮 -->
    <div class="collapse-toggle">
      <el-button @click="toggleCollapse" :icon="isCollapse ? 'el-icon-arrow-right' : 'el-icon-arrow-left'" circle></el-button>
    </div>
  </aside>
</template>

<script>
export default {
  name: 'Aside',
  data() {
    return {
      isCollapse: false,
    };
  },
  computed: {
    sidebarWidth() {
      return this.isCollapse ? '64px' : '200px';
    },
    activeMenu() {
      return this.$store.getters.getActiveMenu;
    },
    openMenus() {
      return this.$store.getters.getOpenMenus;
    }
  },
  watch: {
    '$route'(to) {
      const currentPath = to.path;

      let newActiveMenu = '1-1';
      let newOpenMenus = [...this.openMenus];

      if (currentPath === '/chat') {
        newActiveMenu = '1-1';
        newOpenMenus = ['1'];
      } else if (currentPath === '/admin/forbidden-words') {
        newActiveMenu = '2-1';
        newOpenMenus = ['2'];
      } else if (currentPath === '/user-management') {
        newActiveMenu = '2-3';
        newOpenMenus = ['2'];
      } else if (currentPath === '/user-settings') {
        newActiveMenu = '4';
        newOpenMenus = [];
      }

      this.$store.dispatch('updateActiveMenu', newActiveMenu);
      this.$store.dispatch('updateOpenMenus', newOpenMenus);
    }
  },
  methods: {
    handleOpen(key) {
      const updatedOpenMenus = [...new Set([...this.openMenus, key])];
      this.$store.dispatch('updateOpenMenus', updatedOpenMenus);
    },
    handleClose(key) {
      const updatedOpenMenus = this.openMenus.filter(item => item !== key);
      this.$store.dispatch('updateOpenMenus', updatedOpenMenus);
    },
    toggleCollapse() {
      this.isCollapse = !this.isCollapse;
    },
    navigateTo(route) {
      const targetPath = typeof route === 'string' ? route : this.$router.resolve(route).route.path;

      if (this.$route.path === targetPath) {
        console.warn(`Already at ${targetPath}, skipping navigation.`);
        return;
      }

      this.$router.push(targetPath).catch(err => {
        if (err.name !== 'NavigationDuplicated') {
          console.error('Router push error:', err);
        }
      });
    },
    isCurrentRoute(path) {
      return this.$route.path === path;
    },
    // ✅ 新增方法：跳转并打印日志
    goToUserManagement() {
      const targetPath = '/user-management';

      console.log('Navigating to user management:', targetPath);

      if (this.$route.path !== targetPath) {
        this.$router.push(targetPath).catch(err => {
          if (err.name !== 'NavigationDuplicated') {
            console.error('Navigation error:', err);
          }
        });

        this.$store.dispatch('updateActiveMenu', '2-3');
        this.$store.dispatch('updateOpenMenus', ['2']);
      } else {
        console.warn('Already on /user-management');
      }
    }
  },
  mounted() {
    const currentPath = this.$route.path;

    let newActiveMenu = '1-1';
    let newOpenMenus = [];

    if (currentPath === '/chat') {
      newActiveMenu = '1-1';
      newOpenMenus = ['1'];
    } else if (currentPath === '/admin/forbidden-words') {
      newActiveMenu = '2-1';
      newOpenMenus = ['2'];
    } else if (currentPath === '/user-management') {
      newActiveMenu = '2-3';
      newOpenMenus = ['2'];
    } else if (currentPath === '/user-settings') {
      newActiveMenu = '4';
      newOpenMenus = [];
    }

    this.$store.dispatch('updateActiveMenu', newActiveMenu);
    this.$store.dispatch('updateOpenMenus', newOpenMenus);
  }
};
</script>

<style scoped>
.el-menu {
  border-right: none;
}

.sidebar {
  height: 100%;
  background-color: #545c64;
  position: relative;
}

.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
}

.collapse-toggle {
  position: absolute;
  right: -30px;
  top: 50%;
  transform: translateY(-50%);
}

/* 高亮违禁词设置项 */
.highlight {
  background-color: #4a5056 !important;
  font-weight: bold;
}
</style>